package lock.lock;

import com.sun.corba.se.impl.orbutil.LogKeywords;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author Brook
 */
public class LockDeadLock implements Runnable{

    int flag = 1;
    static Lock lock1 = new ReentrantLock();
    static Lock lock2 = new ReentrantLock();

    public static void main(String[] args) {
        LockDeadLock lock1 = new LockDeadLock();
        LockDeadLock lock2 = new LockDeadLock();
        lock1.flag = 0;
        lock2.flag = 1;
        Thread thread1 = new Thread(lock1);
        Thread thread2 = new Thread(lock2);
        thread1.start();
        thread2.start();
    }

    @Override
    public void run() {

        if(flag == 1){
            try {
                lock1.lock();
                try {
                    System.out.println(Thread.currentThread().getName()+"获取到lock1");
                    Thread.sleep(1000);
                    lock2.lock();
                    try {
                        System.out.println(Thread.currentThread().getName()+"获取到lock2");
                    }finally {
                        lock2.unlock();
                    }
                } finally {
                    lock1.unlock();
                }
            }catch (InterruptedException e) {
                e.printStackTrace();
            }

        }

        if(flag == 0){
            try {
                lock2.lock();
                try {
                    System.out.println(Thread.currentThread().getName()+"获取到lock2");
                    Thread.sleep(1000);
                    lock1.lock();
                    try {
                        System.out.println(Thread.currentThread().getName()+"获取到lock1");
                    }finally {
                        lock1.unlock();
                    }
                } finally {
                    lock2.unlock();
                }
            }catch (InterruptedException e) {
                e.printStackTrace();
            }

        }


    }
}
